package cn.iocoder.yudao.framework.magic.core;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.magic.api.MagicApiExcuse;
import cn.iocoder.yudao.framework.magic.api.dto.ExcuseMagicApiDTO;
import cn.iocoder.yudao.framework.magic.config.config.ResultProviderConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.ssssssss.magicapi.core.service.MagicResourceService;
import org.ssssssss.script.runtime.ExitValue;

import java.util.HashMap;
import java.util.Map;


/**
 * Magic Api 实现类
 *
 */
@Slf4j
public class MagicApiExcuseImpl implements MagicApiExcuse {

    @Autowired
    MagicAPIService magicAPIService;

    @Autowired
    MagicResourceService magicResourceService;

    @Override
    public Object excuseMagicApi(ExcuseMagicApiDTO excuseMagicApiDTO) {

        // // 内部调用接口不包含code以及message信息，同时也不走拦截器。
        Object value = magicAPIService.execute(excuseMagicApiDTO.getMethod(), excuseMagicApiDTO.getPath(), excuseMagicApiDTO.getContext());
        if(value instanceof ExitValue){
            ExitValue res = (ExitValue) value;
            throw new ServiceException((Integer)res.getValues()[0],(String) res.getValues()[1]);
        }
        log.info("调用MagicApi返回结果：{}",value);
        return value;
    }
    @Override
    public Object callMagicApi(ExcuseMagicApiDTO excuseMagicApiDTO) {

        // 内部调用接口包含code以及message信息，同时也不走拦截器。
        Object value = magicAPIService.call(excuseMagicApiDTO.getMethod(), excuseMagicApiDTO.getPath(), excuseMagicApiDTO.getContext());

        if(value instanceof ResultProviderConfig){
            Map res = (HashMap) value;
            if( 0 != (Integer) res.get("code")){
                throw new ServiceException((Integer) res.get("code"),(String) res.get("msg"));
            }else {
                value =  res.get("data");
            }
        }
        log.info("调用MagicApi返回结果：{}",value);

        return value;
    }
}
